// src/components/SettingsModal/index.tsx
import React, { useState } from 'react';
import {
  View,
  Text,
  Modal,
  TouchableOpacity,
  Switch,
  ScrollView,
  StyleSheet,
  Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Toast from 'react-native-toast-message';

interface SettingsModalProps {
  visible: boolean;
  onClose: () => void;
}

interface BaseSettingItem {
  icon: string;
  title: string;
  description: string;
}

interface SwitchSetting extends BaseSettingItem {
  type: 'switch';
  value: boolean;
  onChange: (value: boolean) => void;
}

interface SelectSetting extends BaseSettingItem {
  type: 'select';
  value: string | number;
  onPress: () => void;
}

interface ActionSetting extends BaseSettingItem {
  type: 'action';
  onPress: () => void;
}

type SettingItem = SwitchSetting | SelectSetting | ActionSetting;

interface SettingsSection {
  title: string;
  items: SettingItem[];
}

const SettingsModal: React.FC<SettingsModalProps> = ({
                                                       visible,
                                                       onClose,
                                                     }) => {
  const [notifications, setNotifications] = useState(true);
  const [autoTranslate, setAutoTranslate] = useState(false);
  const [darkMode, setDarkMode] = useState(false);
  const [autoSave, setAutoSave] = useState(true);
  const [streamingMode, setStreamingMode] = useState(true);
  const [selectedLanguage, setSelectedLanguage] = useState('zh-CN');
  const [selectedVoice, setSelectedVoice] = useState('female');
  const [speechRate, setSpeechRate] = useState(1.0);

  const handleClearCache = async () => {
    Alert.alert(
      '清除缓存',
      '确定要清除所有缓存数据吗？',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          style: 'destructive',
          onPress: async () => {
            try {
              await AsyncStorage.clear();
              Toast.show({
                type: 'success',
                text1: '缓存清除成功',
              });
            } catch (error) {
              Toast.show({
                type: 'error',
                text1: '清除失败',
              });
            }
          },
        },
      ]
    );
  };

  const handleResetSettings = () => {
    Alert.alert(
      '重置设置',
      '确定要恢复默认设置吗？',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          style: 'destructive',
          onPress: () => {
            setNotifications(true);
            setAutoTranslate(false);
            setDarkMode(false);
            setAutoSave(true);
            setStreamingMode(true);
            Toast.show({
              type: 'success',
              text1: '设置已重置',
            });
          },
        },
      ]
    );
  };

  const settingsSections: SettingsSection[] = [
    {
      title: '通用设置',
      items: [
        {
          icon: 'notifications',
          title: '推送通知',
          description: '接收重要提醒和更新',
          type: 'switch',
          value: notifications,
          onChange: setNotifications,
        },
        {
          icon: 'dark-mode',
          title: '深色模式',
          description: '减少眼睛疲劳',
          type: 'switch',
          value: darkMode,
          onChange: setDarkMode,
        },
        {
          icon: 'language',
          title: '应用语言',
          description: '选择界面显示语言',
          type: 'select',
          value: selectedLanguage,
          onPress: () => {},
        },
      ],
    },
    {
      title: 'AI设置',
      items: [
        {
          icon: 'translate',
          title: '自动翻译',
          description: '自动检测并翻译文本',
          type: 'switch',
          value: autoTranslate,
          onChange: setAutoTranslate,
        },
        {
          icon: 'save',
          title: '自动保存',
          description: '自动保存聊天记录',
          type: 'switch',
          value: autoSave,
          onChange: setAutoSave,
        },
        {
          icon: 'speed',
          title: '流式输出',
          description: '实时显示AI回复',
          type: 'switch',
          value: streamingMode,
          onChange: setStreamingMode,
        },
      ],
    },
    {
      title: '语音设置',
      items: [
        {
          icon: 'record-voice-over',
          title: '语音类型',
          description: selectedVoice === 'male' ? '男声' : '女声',
          type: 'select',
          value: selectedVoice,
          onPress: () => {},
        },
        {
          icon: 'speed',
          title: '语速',
          description: `${speechRate}x`,
          type: 'select',
          value: speechRate,
          onPress: () => {},
        },
      ],
    },
    {
      title: '存储管理',
      items: [
        {
          icon: 'storage',
          title: '清除缓存',
          description: '释放存储空间',
          type: 'action',
          onPress: handleClearCache,
        },
        {
          icon: 'download',
          title: '下载管理',
          description: '管理离线内容',
          type: 'action',
          onPress: () => {},
        },
      ],
    },
    {
      title: '其他',
      items: [
        {
          icon: 'restore',
          title: '重置设置',
          description: '恢复默认设置',
          type: 'action',
          onPress: handleResetSettings,
        },
      ],
    },
  ];

  return (
    <Modal
      visible={visible}
      transparent
      animationType="slide"
      onRequestClose={onClose}
    >
      <View style={styles.modalOverlay}>
        <View style={styles.modalContent}>
          <View style={styles.modalHeader}>
            <Text style={styles.modalTitle}>设置</Text>
            <TouchableOpacity onPress={onClose}>
              <Icon name="close" size={24} color="#666" />
            </TouchableOpacity>
          </View>

          <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
            {settingsSections.map((section, sectionIndex) => (
              <View key={sectionIndex} style={styles.section}>
                <Text style={styles.sectionTitle}>{section.title}</Text>
                {section.items.map((item, itemIndex) => (
                  <TouchableOpacity
                    key={itemIndex}
                    style={styles.settingItem}
                    onPress={item.type === 'action' || item.type === 'select' ? item.onPress : undefined}
                    activeOpacity={item.type === 'switch' ? 1 : 0.7}
                  >
                    <View style={styles.settingLeft}>
                      <View style={styles.iconContainer}>
                        <Icon name={item.icon} size={20} color="#667eea" />
                      </View>
                      <View style={styles.settingInfo}>
                        <Text style={styles.settingTitle}>{item.title}</Text>
                        <Text style={styles.settingDescription}>{item.description}</Text>
                      </View>
                    </View>
                    {item.type === 'switch' ? (
                      <Switch
                        value={item.value}
                        onValueChange={item.onChange}
                        trackColor={{ false: '#ccc', true: '#667eea' }}
                      />
                    ) : item.type === 'select' ? (
                      <Icon name="chevron-right" size={20} color="#ccc" />
                    ) : item.type === 'action' ? (
                      <Icon name="arrow-forward" size={20} color="#999" />
                    ) : null}
                  </TouchableOpacity>
                ))}
              </View>
            ))}
          </ScrollView>
        </View>
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  modalContent: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    height: '85%',
  },
  modalHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  scrollView: {
    flex: 1,
  },
  section: {
    marginBottom: 20,
  },
  sectionTitle: {
    fontSize: 14,
    color: '#999',
    fontWeight: '600',
    paddingHorizontal: 20,
    paddingVertical: 10,
    backgroundColor: '#f8f9fa',
  },
  settingItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 12,
    paddingHorizontal: 20,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  settingLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  iconContainer: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: '#f0f0ff',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 15,
  },
  settingInfo: {
    flex: 1,
  },
  settingTitle: {
    fontSize: 16,
    color: '#333',
    marginBottom: 3,
  },
  settingDescription: {
    fontSize: 12,
    color: '#999',
  },
});

export default SettingsModal;